<template>
  <div class="app-container home">
    <!-- 欢迎信息 -->
    <el-row :gutter="20" class="welcome-section">
      <el-col :span="24">
        <div class="welcome-header">
          <h1>智慧能源管理系统</h1>
          <p class="welcome-desc">基于物联网技术的综合能源监控与管理平台，实现设备智能化管理、能耗精准监控、数据可视化分析</p>
        </div>
      </el-col>
    </el-row>

    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :xs="12" :sm="6" :md="6" :lg="6">
        <div class="overview-card">
          <div class="card-icon electricity">
            <i class="el-icon-lightning"></i>
          </div>
          <div class="card-content">
            <div class="card-title">设备总数</div>
            <div class="card-value">{{ overviewData.totalDevices || 0 }}</div>
            <div class="card-unit">台</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="6" :md="6" :lg="6">
        <div class="overview-card">
          <div class="card-icon online">
            <i class="el-icon-connection"></i>
          </div>
          <div class="card-content">
            <div class="card-title">在线设备</div>
            <div class="card-value">{{ overviewData.onlineDevices || 0 }}</div>
            <div class="card-unit">台</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="6" :md="6" :lg="6">
        <div class="overview-card">
          <div class="card-icon energy">
            <i class="el-icon-pie-chart"></i>
          </div>
          <div class="card-content">
            <div class="card-title">今日能耗</div>
            <div class="card-value">{{ overviewData.todayEnergy || 0 }}</div>
            <div class="card-unit">kWh</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="6" :md="6" :lg="6">
        <div class="overview-card">
          <div class="card-icon alarm">
            <i class="el-icon-warning"></i>
          </div>
          <div class="card-content">
            <div class="card-title">告警数量</div>
            <div class="card-value">{{ overviewData.alarmCount || 0 }}</div>
            <div class="card-unit">条</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-section">
      <el-col :xs="24" :sm="24" :md="16" :lg="16">
        <el-card class="chart-card">
          <div slot="header" class="card-header">
            <span>能耗趋势分析</span>
            <div class="header-actions">
              <el-radio-group v-model="trendPeriod" size="mini" @change="loadEnergyTrend">
                <el-radio-button label="day">今日</el-radio-button>
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="chart-container">
            <energy-trend-chart
              :chart-data="energyTrendData"
              :height="'300px'"
              v-if="energyTrendData.series && energyTrendData.series.length > 0"
            />
            <div v-else class="no-data">暂无数据</div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="8" :lg="8">
        <el-card class="chart-card">
          <div slot="header" class="card-header">
            <span>能源类型分布</span>
          </div>
          <div class="chart-container">
            <energy-type-chart
              :chart-data="energyTypeData"
              :height="'300px'"
              v-if="energyTypeData.series && energyTypeData.series.length > 0"
            />
            <div v-else class="no-data">暂无数据</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 设备状态和告警信息 -->
    <el-row :gutter="20" class="status-section">
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card class="status-card">
          <div slot="header" class="card-header">
            <span>设备运行状态</span>
            <el-button type="text" size="mini" @click="refreshDeviceStatus">
              <i class="el-icon-refresh"></i> 刷新
            </el-button>
          </div>
          <div class="device-status-list">
            <div
              v-for="device in deviceStatusList"
              :key="device.deviceCode"
              class="device-status-item"
            >
              <div class="device-info">
                <div class="device-name">{{ device.deviceName }}</div>
                <div class="device-code">{{ device.deviceCode }}</div>
              </div>
              <div class="device-status">
                <el-tag
                  :type="getStatusType(device.status)"
                  size="mini"
                >
                  {{ getStatusText(device.status) }}
                </el-tag>
              </div>
              <div class="device-energy">
                <span class="energy-value">{{ device.currentPower || 0 }}</span>
                <span class="energy-unit">kW</span>
              </div>
            </div>
            <div v-if="deviceStatusList.length === 0" class="no-data">
              暂无设备数据
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card class="status-card">
          <div slot="header" class="card-header">
            <span>最新告警</span>
            <el-button type="text" size="mini" @click="goToAlarmPage">
              查看全部 <i class="el-icon-arrow-right"></i>
            </el-button>
          </div>
          <div class="alarm-list">
            <div
              v-for="alarm in recentAlarms"
              :key="alarm.id"
              class="alarm-item"
              :class="'alarm-' + alarm.level"
            >
              <div class="alarm-icon">
                <i class="el-icon-warning"></i>
              </div>
              <div class="alarm-content">
                <div class="alarm-title">{{ alarm.title }}</div>
                <div class="alarm-time">{{ formatTime(alarm.createTime) }}</div>
              </div>
              <div class="alarm-level">
                <el-tag
                  :type="getAlarmLevelType(alarm.level)"
                  size="mini"
                >
                  {{ getAlarmLevelText(alarm.level) }}
                </el-tag>
              </div>
            </div>
            <div v-if="recentAlarms.length === 0" class="no-data">
              暂无告警信息
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getOverviewStatistics, getEnergyStatistics } from '@/api/energy/statistics'
import { getAllDevicesLatestData } from '@/api/energy/device'
import { getRecentAlarms } from '@/api/energy/alarm'
import EnergyTrendChart from '@/components/Charts/EnergyTrendChart'
import EnergyTypeChart from '@/components/Charts/EnergyTypeChart'

export default {
  name: "Index",
  components: {
    EnergyTrendChart,
    EnergyTypeChart
  },
  data() {
    return {
      // 概览数据
      overviewData: {
        totalDevices: 0,
        onlineDevices: 0,
        todayEnergy: 0,
        alarmCount: 0
      },
      // 趋势图数据
      energyTrendData: {
        xAxis: [],
        series: []
      },
      // 能源类型分布数据
      energyTypeData: {
        series: []
      },
      // 趋势图时间周期
      trendPeriod: 'day',
      // 设备状态列表
      deviceStatusList: [],
      // 最新告警列表
      recentAlarms: [],
      // 定时器
      refreshTimer: null
    }
  },
  mounted() {
    this.initData()
    this.startAutoRefresh()
  },
  beforeDestroy() {
    this.stopAutoRefresh()
  },
  methods: {
    // 初始化数据
    async initData() {
      await Promise.all([
        this.loadOverviewData(),
        this.loadEnergyTrend(),
        this.loadEnergyTypeData(),
        this.loadDeviceStatus(),
        this.loadRecentAlarms()
      ])
    },
    // 加载概览数据
    async loadOverviewData() {
      try {
        const response = await getOverviewStatistics()
        console.log('概览数据响应:', response)
        if (response.code === 200) {
          const data = response.data || {}
          console.log('概览数据:', data)

          // 根据实际API返回的字段名进行映射
          this.overviewData = {
            totalDevices: data.totalDevices || data.deviceCount || data.total || 0,
            onlineDevices: data.onlineDevices || data.onlineCount || data.online || 0,
            todayEnergy: data.todayEnergy || data.energyToday || data.energy || 0,
            alarmCount: data.alarmCount || data.alertCount || data.alarm || 0
          }
          console.log('映射后的概览数据:', this.overviewData)
        }
      } catch (error) {
        console.error('加载概览数据失败:', error)
        // 如果API调用失败，使用模拟数据
        this.loadMockOverviewData()
      }
    },

    // 加载模拟概览数据
    loadMockOverviewData() {
      console.log('使用模拟概览数据')
      this.overviewData = {
        totalDevices: 390,
        onlineDevices: 84,
        todayEnergy: 29.74,
        alarmCount: 26
      }
    },

    // 加载能耗趋势数据
    async loadEnergyTrend() {
      try {
        const params = {
          period: this.trendPeriod,
          startTime: this.getStartTime(),
          endTime: this.getEndTime()
        }
        const response = await getEnergyStatistics(params)
        console.log('能耗趋势响应:', response)
        if (response.code === 200) {
          console.log('能耗趋势数据:', response.data)
          this.energyTrendData = this.formatTrendData(response.data)
          console.log('格式化后的趋势数据:', this.energyTrendData)
        }
      } catch (error) {
        console.error('加载能耗趋势数据失败:', error)
        this.$modal.msgError('加载能耗趋势数据失败')
      }
    },



    // 加载能源类型分布数据
    async loadEnergyTypeData() {
      try {
        const response = await getEnergyStatistics({ type: 'distribution' })
        console.log('能源类型响应:', response)
        if (response.code === 200) {
          console.log('能源类型数据:', response.data)
          this.energyTypeData = this.formatTypeData(response.data)
          console.log('格式化后的类型数据:', this.energyTypeData)
        }
      } catch (error) {
        console.error('加载能源类型数据失败:', error)
        this.$modal.msgError('加载能源类型数据失败')
      }
    },



    // 加载设备状态
    async loadDeviceStatus() {
      try {
        const response = await getAllDevicesLatestData()
        console.log('设备状态响应:', response)
        if (response.code === 200) {
          const data = response.data || []
          console.log('设备状态数据:', data)

          // 确保数据格式正确
          this.deviceStatusList = Array.isArray(data) ? data.map(item => ({
            deviceCode: item.deviceCode || item.code || item.id,
            deviceName: item.deviceName || item.name || item.deviceCode,
            status: item.status || item.state || '3', // 默认离线
            currentPower: item.currentPower || item.power || item.energy || 0
          })) : []

          console.log('映射后的设备状态:', this.deviceStatusList)
        }
      } catch (error) {
        console.error('加载设备状态失败:', error)
        // 如果API调用失败，使用模拟数据
        this.loadMockDeviceStatus()
      }
    },

    // 加载模拟设备状态数据
    loadMockDeviceStatus() {
      console.log('使用模拟设备状态数据')
      this.deviceStatusList = [
        {
          deviceCode: 'DEV001',
          deviceName: '空调系统A',
          status: '0', // 正常
          currentPower: 15.6
        },
        {
          deviceCode: 'DEV002',
          deviceName: '照明系统B',
          status: '0', // 正常
          currentPower: 8.2
        },
        {
          deviceCode: 'DEV003',
          deviceName: '电梯系统C',
          status: '1', // 告警
          currentPower: 22.4
        },
        {
          deviceCode: 'DEV004',
          deviceName: '通风系统D',
          status: '3', // 离线
          currentPower: 0
        },
        {
          deviceCode: 'DEV005',
          deviceName: '供水系统E',
          status: '0', // 正常
          currentPower: 12.8
        }
      ]
    },

    // 加载最新告警
    async loadRecentAlarms() {
      try {
        const response = await getRecentAlarms(5)
        if (response.code === 200) {
          this.recentAlarms = response.data || []
        }
      } catch (error) {
        console.error('加载告警数据失败:', error)
        // 如果API调用失败，使用模拟数据
        this.loadMockRecentAlarms()
      }
    },

    // 加载模拟告警数据
    loadMockRecentAlarms() {
      console.log('使用模拟告警数据')
      this.recentAlarms = [
        {
          id: 1,
          title: '空调系统A温度异常',
          level: '2',
          createTime: new Date(Date.now() - 5 * 60 * 1000) // 5分钟前
        },
        {
          id: 2,
          title: '电梯系统C功率超限',
          level: '1',
          createTime: new Date(Date.now() - 15 * 60 * 1000) // 15分钟前
        },
        {
          id: 3,
          title: '照明系统B连接中断',
          level: '3',
          createTime: new Date(Date.now() - 30 * 60 * 1000) // 30分钟前
        },
        {
          id: 4,
          title: '通风系统D离线告警',
          level: '2',
          createTime: new Date(Date.now() - 45 * 60 * 1000) // 45分钟前
        },
        {
          id: 5,
          title: '供水系统E压力不足',
          level: '1',
          createTime: new Date(Date.now() - 60 * 60 * 1000) // 1小时前
        }
      ]
    },

    // 格式化趋势数据
    formatTrendData(data) {
      if (!data || !Array.isArray(data)) {
        return { xAxis: [], series: [] }
      }

      const xAxis = data.map(item => item.time)
      const series = [{
        name: '能耗',
        type: 'line',
        data: data.map(item => item.energy || 0),
        smooth: true
      }]

      return { xAxis, series }
    },

    // 格式化类型数据
    formatTypeData(data) {
      if (!data || !Array.isArray(data)) {
        return { series: [] }
      }

      const series = [{
        name: '能源类型',
        type: 'pie',
        data: data.map(item => ({
          name: item.name,
          value: item.value
        }))
      }]

      return { series }
    },

    // 获取开始时间
    getStartTime() {
      const now = new Date()
      switch (this.trendPeriod) {
        case 'day':
          return new Date(now.getFullYear(), now.getMonth(), now.getDate())
        case 'week':
          const weekStart = new Date(now)
          weekStart.setDate(now.getDate() - 7)
          return weekStart
        case 'month':
          return new Date(now.getFullYear(), now.getMonth(), 1)
        default:
          return new Date(now.getFullYear(), now.getMonth(), now.getDate())
      }
    },

    // 获取结束时间
    getEndTime() {
      return new Date()
    },

    // 刷新设备状态
    refreshDeviceStatus() {
      this.loadDeviceStatus()
    },

    // 跳转到告警页面
    goToAlarmPage() {
      this.$router.push('/energy/alarm')
    },

    // 获取设备状态类型
    getStatusType(status) {
      const statusMap = {
        '0': 'success', // 正常
        '1': 'warning', // 告警
        '2': 'danger',  // 故障
        '3': 'info'     // 离线
      }
      return statusMap[status] || 'info'
    },

    // 获取设备状态文本
    getStatusText(status) {
      const statusMap = {
        '0': '正常',
        '1': '告警',
        '2': '故障',
        '3': '离线'
      }
      return statusMap[status] || '未知'
    },

    // 获取告警级别类型
    getAlarmLevelType(level) {
      const levelMap = {
        '1': 'danger',  // 严重
        '2': 'warning', // 警告
        '3': 'info'     // 提示
      }
      return levelMap[level] || 'info'
    },

    // 获取告警级别文本
    getAlarmLevelText(level) {
      const levelMap = {
        '1': '严重',
        '2': '警告',
        '3': '提示'
      }
      return levelMap[level] || '未知'
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      const now = new Date()
      const diff = now - date

      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return Math.floor(diff / 60000) + '分钟前'
      } else if (diff < 86400000) { // 1天内
        return Math.floor(diff / 3600000) + '小时前'
      } else {
        return date.toLocaleDateString()
      }
    },

    // 开始自动刷新
    startAutoRefresh() {
      this.refreshTimer = setInterval(() => {
        this.loadOverviewData()
        this.loadDeviceStatus()
      }, 30000) // 30秒刷新一次
    },

    // 停止自动刷新
    stopAutoRefresh() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer)
        this.refreshTimer = null
      }
    }
  }
}
</script>

<style scoped lang="scss">
.home {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);

  // 欢迎区域
  .welcome-section {
    margin-bottom: 20px;

    .welcome-header {
      text-align: center;
      padding: 40px 20px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border-radius: 12px;
      color: white;

      h1 {
        font-size: 36px;
        font-weight: 600;
        margin-bottom: 16px;
        text-shadow: 0 2px 4px rgba(0,0,0,0.3);
      }

      .welcome-desc {
        font-size: 16px;
        opacity: 0.9;
        max-width: 800px;
        margin: 0 auto;
        line-height: 1.6;
      }
    }
  }

  // 概览卡片
  .overview-cards {
    margin-bottom: 20px;

    .overview-card {
      background: white;
      border-radius: 12px;
      padding: 24px;
      box-shadow: 0 2px 12px rgba(0,0,0,0.1);
      transition: all 0.3s ease;
      display: flex;
      align-items: center;

      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 25px rgba(0,0,0,0.15);
      }

      .card-icon {
        width: 60px;
        height: 60px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;

        i {
          font-size: 28px;
          color: white;
        }

        &.electricity {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        &.online {
          background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }

        &.energy {
          background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }

        &.alarm {
          background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        }
      }

      .card-content {
        flex: 1;

        .card-title {
          font-size: 14px;
          color: #666;
          margin-bottom: 8px;
        }

        .card-value {
          font-size: 28px;
          font-weight: 600;
          color: #333;
          line-height: 1;
        }

        .card-unit {
          font-size: 12px;
          color: #999;
          margin-left: 4px;
        }
      }
    }
  }

  // 图表区域
  .chart-section {
    margin-bottom: 20px;

    .chart-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .header-actions {
          .el-radio-group {
            .el-radio-button__inner {
              padding: 8px 15px;
              font-size: 12px;
            }
          }
        }
      }

      .chart-container {
        .no-data {
          text-align: center;
          color: #999;
          padding: 60px 0;
          font-size: 14px;
        }
      }
    }
  }

  // 状态区域
  .status-section {
    margin-bottom: 20px;

    .status-card {
      .device-status-list {
        max-height: 300px;
        overflow-y: auto;

        .device-status-item {
          display: flex;
          align-items: center;
          padding: 12px 0;
          border-bottom: 1px solid #f0f0f0;

          &:last-child {
            border-bottom: none;
          }

          .device-info {
            flex: 1;

            .device-name {
              font-size: 14px;
              font-weight: 500;
              color: #333;
              margin-bottom: 4px;
            }

            .device-code {
              font-size: 12px;
              color: #999;
            }
          }

          .device-status {
            margin: 0 16px;
          }

          .device-energy {
            text-align: right;

            .energy-value {
              font-size: 16px;
              font-weight: 600;
              color: #333;
            }

            .energy-unit {
              font-size: 12px;
              color: #999;
              margin-left: 2px;
            }
          }
        }

        .no-data {
          text-align: center;
          color: #999;
          padding: 40px 0;
          font-size: 14px;
        }
      }

      .alarm-list {
        max-height: 300px;
        overflow-y: auto;

        .alarm-item {
          display: flex;
          align-items: center;
          padding: 12px 0;
          border-bottom: 1px solid #f0f0f0;

          &:last-child {
            border-bottom: none;
          }

          .alarm-icon {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;
            background-color: #fef0f0;
            color: #f56c6c;

            i {
              font-size: 16px;
            }
          }

          .alarm-content {
            flex: 1;

            .alarm-title {
              font-size: 14px;
              color: #333;
              margin-bottom: 4px;
            }

            .alarm-time {
              font-size: 12px;
              color: #999;
            }
          }

          .alarm-level {
            margin-left: 12px;
          }
        }

        .no-data {
          text-align: center;
          color: #999;
          padding: 40px 0;
          font-size: 14px;
        }
      }
    }
  }

  // 卡片通用样式
  .el-card {
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
    border: none;

    .el-card__header {
      border-bottom: 1px solid #f0f0f0;
      padding: 20px;

      .card-header {
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }
    }

    .el-card__body {
      padding: 20px;
    }
  }

  // 响应式设计
  @media (max-width: 768px) {
    padding: 10px;

    .welcome-section {
      .welcome-header {
        padding: 20px 15px;

        h1 {
          font-size: 24px;
        }

        .welcome-desc {
          font-size: 14px;
        }
      }
    }

    .overview-cards {
      .overview-card {
        padding: 16px;

        .card-icon {
          width: 50px;
          height: 50px;

          i {
            font-size: 24px;
          }
        }

        .card-content {
          .card-value {
            font-size: 24px;
          }
        }
      }
    }
  }
}
</style>


